import base64
#from Crypto.Cipher import AES
#from Cryptodome.Cipher import AES
from Crypto.Cipher import AES
def add_to_16(value):
    BS = AES.block_size
    x=chr(BS - len(value) % BS)
    while len(value) % 16 != 0:
        value += x
    return str.encode(value)  # 返回bytes

class PrpCrypt(object):


    encSecKey = '2d48fd9fb8e58bc9c1f14a7bda1b8e49a3520a67a2300a1f73766caee29f2411c5350bceb15ed196ca963d6a6d0b61f3734f0a0f4a172ad853f16dd06018bc5ca8fb640eaa8decd1cd41f66e166cea7a3023bd63960e656ec97751cfc7ce08d943928e9db9b35400ff3d138bda1ab511a06fbee75585191cabe0e6e63f7350d6'

    def __init__(self, key,iv):
        self.key = key.encode('utf-8')
        self.mode = AES.MODE_CBC
        self.iv=iv

    # 加密函数，如果text不足16位就用空格补足为16位，
    # 如果大于16当时不是16的倍数，那就补足为16的倍数。
    def encrypt(self, text):

        BS = AES.block_size
        pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
        unpad = lambda s: s[0:-ord(s[-1])]

        cryptor = AES.new(self.key, self.mode,self.iv)
        self.ciphertext = cryptor.encrypt(add_to_16(text))
        encrypted_text = str(base64.encodebytes(self.ciphertext), encoding='utf-8')  # 执行加密并转码返回bytes
        return (encrypted_text)
        #return (self.ciphertext)

    # 解密后，去掉补足的空格用strip() 去掉
    def decrypt(self, text):
        cryptor = AES.new(self.key, self.mode,self.iv)
        plain_text = cryptor.decrypt((text))
        # return plain_text.rstrip('\0')
        return bytes.decode(plain_text).rstrip('\0')

    @classmethod
    def get_encrypt_params(cls,text):
        # 第一次AES加密秘钥不变
        key1 = '0CoJUm6Qyw8W8jud'
        # 第二次AES加密秘钥
        key2 = 'a8LWv2uAtXjzSfkQ'
        # 两次加密秘钥的偏移量
        iv = b'0102030405060708'

        pc1 = PrpCrypt(key1, iv)  # 初始化密钥和iv
        e1 = pc1.encrypt(text)  # 加密
        e1 = e1.replace("\n", "")

        pc2 = PrpCrypt(key2, iv)  # 初始化密钥和iv
        e2 = pc2.encrypt(e1)  # 加密
        e2 = e2.replace("\n", "")
        return e2


if __name__ == '__main__':
    key='0CoJUm6Qyw8W8jud'  #秘钥 0CoJUm6Qyw8W8jud
    iv=b'0102030405060708'  #iv
    pc = PrpCrypt(key,iv)  # 初始化密钥和iv
    e = pc.encrypt('{"userId":"1","offset":"0","total":"true","limit":"20"}')  # 加密
    d = pc.decrypt(pc.ciphertext)  # 解密
    e=e.replace("\n","")
   # base64加密超过一定长度会自动换行 需要去除换行符
    print("第一次加密:", e)
    #print("解密:", d)

    keyy = 'a8LWv2uAtXjzSfkQ'  # 秘钥
    pcc = PrpCrypt(keyy, iv)  # 初始化密钥和iv
    ee = pcc.encrypt(e)  # 加密
    ee = ee.replace("\n", "")
    #print("第二次加密:", ee)

    #print("url编码:",parse.quote(ee))
